package api

import (
	"gitee.com/go-mao/mao/demo/app/modules/demo/components/user"
	"gitee.com/go-mao/mao/demo/app/modules/demo/controller/hooks"
	"gitee.com/go-mao/mao/demo/app/modules/demo/service"
	"gitee.com/go-mao/mao/frame"
	"gitee.com/go-mao/mao/libs/try"
	"github.com/gin-gonic/gin"
)

type UserController struct {
}

// 获取配置
func (UserController) Config(w *frame.Webline) {
	userService := service.NewUserService(w.Taskline)
	config := userService.Config()
	w.JSON(100, config, "ok")
}

// 获取权限
func (UserController) GetPermision(w *frame.Webline) {
	w.JSON(100, w.GetPermissionList(), "ok")
}

// 创建用户
func (UserController) Create(w *frame.Webline) {
	var req struct {
		Username string `bind:"username" valid:"required->用户不能为空"`
	}
	w.BindJSON(&req)
	userService := service.NewUserService(w.Taskline)
	var userEntity *user.User
	w.Transaction(func() {
		userEntity = userService.UserDomain().Create(req.Username)
		w.PutHook(&hooks.AfterCreateUserHook{UserName: req.Username})
	})
	w.JSON(100, gin.H{
		"id":    userEntity.Id,
		"route": w.GetRouterName(),
	}, "ok")
}

// 查询单个用户
func (UserController) Get(w *frame.Webline) {
	var req struct {
		Id int64 `bind:"id" valid:"required->编号不能为空"`
	}
	w.BindQuery(&req)
	userService := service.NewUserService(w.Taskline)
	userEntity, ok := userService.UserDomain().Get(req.Id)
	if !ok {
		try.Throw(frame.CODE_WARN, "用户无效")
	}
	w.JSON(200, userEntity)
}

// 修改用户
func (UserController) Update(w *frame.Webline) {
	var req struct {
		Id       int64  `bind:"id" valid:"required->编号不能为空"`
		Username string `bind:"username" valid:"required->用户不能为空"`
	}
	w.BindJSON(&req)
	userService := service.NewUserService(w.Taskline)
	userService.UserDomain().Update(req.Id, req.Username)
	w.JSON(200, nil, "ok")
}

// 删除用户
func (UserController) Remove(w *frame.Webline) {
	var req struct {
		Id int64 `bind:"id" valid:"required->编号不能为空"`
	}
	w.BindJSON(&req)
	userService := service.NewUserService(w.Taskline)
	userService.UserDomain().Remove(req.Id)
	w.JSON(200, nil, "ok")
}

// 查询所有用户
func (UserController) Find(w *frame.Webline) {
	var req struct {
		Username string `bind:"username"`
		frame.BaseQuery
	}
	w.BindQuery(&req)
	userService := service.NewUserService(w.Taskline)
	list := make([]user.User, 0)
	total := userService.UserDomain().Find(req.Username, &list, req.Page, req.Limit)
	w.JSON(200, gin.H{
		"data":  list,
		"total": total,
	}, "ok")
}
